/*
 * Copyright 2008-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.baturu.mybatisminus.injector.parser;

import com.baturu.mybatisminus.base.Sort;
import com.baturu.mybatisminus.model.TableInfo;
import org.springframework.util.StringUtils;
import com.baturu.mybatisminus.base.Sort.*;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


class OrderBySource {

	private static final String BLOCK_SPLIT = "(?<=Asc|Desc)(?=\\p{Lu})";
	private static final Pattern DIRECTION_SPLIT = Pattern.compile("(.+?)(Asc|Desc)?$");
	private static final String INVALID_ORDER_SYNTAX = "Invalid order syntax for part %s!";
	private static final Set<String> DIRECTION_KEYWORDS = new HashSet<>(Arrays.asList("Asc", "Desc"));

	private final List<Order> orders;


	OrderBySource(String clause, TableInfo tableInfo) {

		this.orders = new ArrayList<>();

		if (!StringUtils.hasText(clause)) {
			return;
		}

		for (String part : clause.split(BLOCK_SPLIT)) {

			Matcher matcher = DIRECTION_SPLIT.matcher(part);

			if (!matcher.find()) {
				throw new IllegalArgumentException(String.format(INVALID_ORDER_SYNTAX, part));
			}

			String propertyString = matcher.group(1);
			String directionString = matcher.group(2);

			if (DIRECTION_KEYWORDS.contains(propertyString) && directionString == null) {
				throw new IllegalArgumentException(String.format(INVALID_ORDER_SYNTAX, part));
			}

			this.orders.add(createOrder(propertyString, Direction.fromOptionalString(directionString), tableInfo));
		}
	}


    private Order createOrder(String property, Optional<Direction> direction, TableInfo tableInfo) {
        property = StringUtils.uncapitalize(property);
        if(tableInfo.containsProperty(property)) {
            property = tableInfo.getFieldInfo(property).getColumn();
        }
        String finalProperty = property;
        return direction.map(direct -> new Order(direct, finalProperty))
                .orElseGet(() -> Order.by(finalProperty));
    }

	Sort toSort() {
		return Sort.by(this.orders);
	}

	@Override
	public String toString() {
		return "Order By " + StringUtils.collectionToDelimitedString(orders, ", ");
	}
}
